<?php
require_once(ROOT_DIR."/dao/db.php");
define("SINA_WB_AKEY", '4232902482');
define("SINA_WB_SKEY", '557c4f46efad13d3f8f9717f11ed47f6');
class LSina {
	
	/**
	 * 新浪微博影响力计算公式
	 */
	static private function calculateWeight($friends, $followers, $statuses, $create_time, $verified){
		return round($followers*0.9 + $friends*0.05 + $statuses*0.05);
	}
	
	/**
	 * 获取验证的url
	 */
	static public function getAuthUrl($callbackUrl){
		require_once("lib/sina/weibooauth.class.php");
		$o = new WeiboOAuth(SINA_WB_AKEY, SINA_WB_SKEY);
		$keys = $o->getRequestToken();
		$_SESSION['keys'] = $keys;
		$aurl = $o->getAuthorizeURL($keys['oauth_token'] ,false , $callbackUrl);
		return $aurl;
	}

    /**
	 * 用verifier去连接新浪微博，同时更新用户信息，保存进数据库
	 * @param user_id 返回本地的用户ID
	 * @return array|false 同步到的信息
	 */
	static public function connect(&$user_id, $oauth_token, $oauth_token_secret){
		require_once("lib/sina/weibooauth.class.php");
		$o = new WeiboOAuth(SINA_WB_AKEY , SINA_WB_SKEY , $oauth_token , $oauth_token_secret);
		$auth_keys = $o->getAccessToken($_REQUEST['oauth_verifier']);
		$c = new WeiboClient(SINA_WB_AKEY, SINA_WB_SKEY, $auth_keys['oauth_token'], $auth_keys['oauth_token_secret']);
		$userInfo = $c->show_user($auth_keys['user_id']);
		// 用token去检索数据库
		$sql = "select * from sync_sina where oauth_token='{$auth_keys['oauth_token']}'";
		$row = DB::getRow($sql);
		if($row){
			if($user_id){
				// 合并合步
				DB::query("update sync_sina set user_id={$user_id} where oauth_token='{$auth_keys['oauth_token']}'");
				// 修改该记录的user_id为合并合的ID
				DB::query("update user set sina=1 where user_id={$user_id}");
				// 删除原来那条同步记录
				DB::query("delete user where user_id={$row['user_id']}");
			}else{
				$user_id = $row['user_id'];
			}
			// 有记录
			$sql = "update sync_sina set friends={friends},followers={followers},statuses={statuses},verified={verified}"
					.",weight={weight},last_sync={last_sync} where user_id={user_id}";
			
			$sql = strtr($sql, array(
				'{friends}' => $userInfo['friends_count'],
				'{followers}' => $userInfo['followers_count'],
				'{statuses}' => $userInfo['followers_count'],
				'{verified}' => (int)$userInfo['verified'],
				'{weight}' => self::calculateWeight($userInfo['friends_count'], $userInfo['followers_count'], $userInfo['followers_count'], strtotime($userInfo['created_at']), (int)$userInfo['verified']),
				'{last_sync}' => time(),
				'{user_id}' => $user_id,
			));
			if(DB::query($sql)){
				$array = DB::getRow("select * from sync_sina where user_id={$user_id}");
				return $array;
			}else{
				return false;
			}
		} else {
			if($user_id){
				// 已经同步了其它的平台,把这个平台的同步置1
				$sql = "update user set sina=1 where user_id={$user_id}";
				$ret = DB::query($sql);
			} else {
				// 新用户
				// 在user表里插入一条新记录，获取user_id
				$sql = "insert into user(sina) values(1)";
				$ret = DB::query($sql) or die("insert new user error!");
				$user_id = DB::newInsertId();
			}
			// 在sync_sina表里插入记录
			$sql = "insert into sync_sina(user_id,sina_uid,oauth_token,oauth_token_secret,friends,followers,statuses,sina_create_time,verified,weight,last_sync,create_time,name) "
					." values({user_id},{sina_uid},'{oauth_token}','{oauth_token_secret}',{friends},{followers},{statuses},"
					."{sina_create_time},{verified},{weight},{last_sync},{create_time},'{name}')";
			$sql = strtr($sql, array(
				'{user_id}' => $user_id,
				'{sina_uid}' => $auth_keys['user_id'],
				'{oauth_token}' => $auth_keys['oauth_token'],
				'{oauth_token_secret}' => $auth_keys['oauth_token_secret'],
				'{friends}' => $userInfo['friends_count'],
				'{followers}' => $userInfo['followers_count'],
				'{statuses}' => $userInfo['statuses_count'],
				'{sina_create_time}' => strtotime($userInfo['created_at']),
				'{verified}' => (int)$userInfo['verified'],
				'{weight}' => self::calculateWeight($userInfo['friends_count'], $userInfo['followers_count'], $userInfo['statuses_count'], strtotime($userInfo['created_at']), (int)$userInfo['verified']),
				'{last_sync}' => time(),
				'{create_time}' => time(),
				'{name}' => $userInfo['name'],
			));
			if(DB::query($sql)){
				$array = DB::getRow("select * from sync_sina where user_id={$user_id}");
				return $array;
			}else{
				return false;
			}
		}
	}
	
	/**
	 * 发布消息
	 */
	static public function publish($user_id, $msg){
		// 发布信息
		$renrenTmp = Table::Fetch('sync_sina', $user_id);
		require_once("lib/sina/weibooauth.class.php");
		$c = new WeiboClient(SINA_WB_AKEY, SINA_WB_SKEY, $renrenTmp['oauth_token'], $renrenTmp['oauth_token_secret']);
		$rr = $c->update($msg);
		if($rr['error_code']){
			if(($rr['error_code'] == '401') ||($rr['error_code'] == '402')){
				// 授权已取消或微博不存在，则删除同步记录
				LSync::Disconnect($user_id, "sina");
			}
			return $rr;
		} else{
			return Table::UpdateCache('sync_sina', $user_id, array(
						'friends' => $rr['user']['friends_count'],
						'followers' => $rr['user']['followers_count'],
						'statuses' => $rr['user']['followers_count'],
						'verified' => (int)$rr['user']['verified'],
						'weight' => self::calculateWeight($rr['user']['friends_count'], $rr['user']['followers_count'], $rr['user']['statuses_count'], strtotime($rr['user']['created_at']), (int)$rr['user']['verified']),
						'last_sync' => time(),
					));
		}
	}
}
?>